package com.newer.weatherforecast.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class BaseDAO {
	SQLiteDatabase sqlDB = null;
	public static final int VERSION = 1;
	public static final String DBNAME = "weatherforecast.db";
	public static final String CONFIG = "config";
	public static final String SMS = "sms";
	public static final String CITY = "cityinfo";
	public static final String TABLE_CONFIG = "create table " + CONFIG + "(" +
								"_id integer primary key autoincrement," +
								"allow_auto_refresh bit default(1)," +
								"auto_refreshFreg integer default(24)," +
								"allow_send_msg bit default(1)," +
								"save_msg bit default(1)," +
								"msg_keyword text default('TQ')," +
								"close_tips bit default(0))";
	public static final String TABLE_SMS = "create table " + SMS + "(" +
								"_id integer primary key  autoincrement , " +
								"sms_num text not null," +
								"sms_body text," +
								"sms_name text," +
								"receive_time text," +
								"return_result text)";
	public static final String TABLE_CITY = "create table " + CITY + "(" +
								"_id integer primary key autoincrement ," +
								"city_name text," +
								"current_city bit," +
								"last_update_time text," +
								"last_tempreture text," +
								"last_weather text," +
								"last_icon integer)";
	public BaseDAO(Context context){
		MySqliteOpenHelper msoh = new MySqliteOpenHelper(context, DBNAME, null, VERSION);
		try {
			sqlDB = msoh.getWritableDatabase();
		} catch (Exception e) {
			sqlDB = msoh.getReadableDatabase();
			e.printStackTrace();
		}
	}
	class MySqliteOpenHelper extends SQLiteOpenHelper{
		public MySqliteOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(TABLE_CITY);
			db.execSQL(TABLE_CONFIG);
			db.execSQL(TABLE_SMS);
		}
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop if exists " + CONFIG);
			db.execSQL("drop if exists " + CITY);
			db.execSQL("drop if exists " + SMS);
			onCreate(db);
		}
	}
	public void close(){
		sqlDB.close();
	}
}
